package com.xhlj.security.captcha;

import cn.hutool.log.Log;
import com.xhlj.utils.RedisKey;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class CaptchaLoginAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication instanceof CaptchaLoginAuthenticationToken) {
            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
            HashMap principal = (HashMap) authentication.getPrincipal();
            String phone = (String) principal.get("phone");
            String captcha = (String) principal.get("code");

//          获取正确的验证码,可能是从redis key:const   value:123456
//          TODO:从redis中读取验证码
                String key = RedisKey.Login_captcha_prefix + phone;
                String redisCode = stringStringValueOperations.get(key);
                if(redisCode==null)
                    throw new DisabledException("验证码不存在，请先发送");
                if(!redisCode.equals(captcha))
                    throw new DisabledException("验证码不正确，请重新输入");
                if (redisCode != null && redisCode.equals(captcha)) {
//              验证成功
                    System.out.println("验证码验证成功");
                    stringRedisTemplate.delete(key);
                    authentication.setAuthenticated(true);
                    return authentication;
                }
            }
        authentication.setAuthenticated(false);
        return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CaptchaLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
